package teacher.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import teacher.actionform.NoticeForm;
import dao.NoticeMagDao;
import dao.impl.NoticeMagImpl;
import domain.Notice;
import domain.Teacher;

/**
 * 管理公告的Action
 * 
 * May 27, 2009
 *
 * @author Fabian
 *
 */
public class ManagerNoticeAction extends DispatchAction {
	/**
	 * 浏览所有公告的Action，但是要传递分页参数（start--开始，limit--间隔）
	 */
	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		NoticeForm nf = (NoticeForm)form;
		int start = nf.getStart();
		int limit = nf.getLimit();			
		
		NoticeMagDao nmd = new NoticeMagImpl();
		//获取此页面的Notice
		List<Notice> list = nmd.getPageNotice(start, limit);
		//获取总记录数
		int totalCount = nmd.getTotalCount();
		
		//组装JSON字符串，返回
		String resultArray = "";
		for (Iterator<Notice> it = list.iterator(); it.hasNext(); ) {
			Notice n = it.next();
			Date pub_time = n.getPub_time();
			Date end_time = n.getEnd_time();
			long p = pub_time.getTime();
			long e = end_time.getTime();
			
			resultArray = resultArray + "{id: " + n.getId() + ", pub_time: new Date(" + p +
							"), end_time: new Date(" + e + "), status: '" + n.getStatus() +
							"', author: '" + n.getAuthor() + "', role: '" + n.getRole() +
							"', content: '" + n.getContent() + "'}";
			if (it.hasNext()) {
				resultArray = resultArray + ",";
			}			
		}
		
		String jsonStr = "";
		jsonStr = "{totalProperty: " + totalCount + ", root: [ " + resultArray + " ]}";
		
		request.setAttribute("result", jsonStr);
				
		return mapping.findForward("show_result");
	}
	
	/**
	 * 添加公告
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		NoticeForm nf = (NoticeForm)form;
		Notice n = new Notice();
		
		n.setContent(nf.getContent());
		SimpleDateFormat sdf = new SimpleDateFormat("yy年MM月dd日");
		n.setEnd_time(sdf.parse(nf.getEnd_time()));
		
		//获取发布人的信息
		HttpSession session = request.getSession();
		Teacher tch = (Teacher)session.getAttribute("user");
		
		n.setAuth_id(tch.getId());
		
		NoticeMagDao nmd = new NoticeMagImpl();
		boolean result = nmd.addNotice(n);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{success: true, msg: '恭喜，发布公告成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{failure: true, msg: '抱歉，发布公告失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		return mapping.findForward("add_result");
	}
	
	/**
	 * 修改更新公告数据
	 */
	public ActionForward modify(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		NoticeForm nf = (NoticeForm)form;
		Notice n = new Notice();
		
		n.setId(nf.getId());
		n.setContent(nf.getContent());
		SimpleDateFormat sdf = new SimpleDateFormat("yy年MM月dd日");
		n.setEnd_time(sdf.parse(nf.getEnd_time()));
		
		NoticeMagDao nmd = new NoticeMagImpl();
		boolean result = nmd.modifyNotice(n);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{success: true, msg: '恭喜，修改公告信息成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{failure: true, msg: '抱歉，修改公告信息失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		return mapping.findForward("modify_result");
	}
	
	/**
	 * 删除公告
	 */
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		NoticeForm nf = (NoticeForm)form;		
		int del_id = nf.getId();
		
		NoticeMagDao nmd = new NoticeMagImpl();
		boolean result = nmd.delNotice(del_id);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{result: 'success', msg: '恭喜，删除公告成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{result: 'failure', msg: '抱歉，删除公告失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		
		return mapping.findForward("del_result");
	}
	
	/**
	 * 登陆后显示公告信息
	 */
	public ActionForward display(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		NoticeMagDao nmd = new NoticeMagImpl();
		List<Notice> list = nmd.displayNotice();
		
		//组装JSON字符串，返回		
		String jsonStr = "";
		//用于上一条，下一条
		String ids = "[";
		if (list.size() > 0) {
			String resultArray = "";
			for (Iterator<Notice> it = list.iterator(); it.hasNext(); ) {
				Notice n = it.next();
				Date pub_time = n.getPub_time();
				Date end_time = n.getEnd_time();
				long p = pub_time.getTime();
				long e = end_time.getTime();
				
				resultArray = resultArray + "{id: 'card-" + n.getId() + "', html: '<br/><h1>发布人：<font color=blue>" + 
								n.getAuthor() + "</font></h1><br/><h1>内容：</h1><br/>" + n.getContent() + "'}";
				if (it.hasNext()) {
					resultArray = resultArray + ",";
				}		
				
				ids = ids + "'card-" + n.getId() + "'";
				if (it.hasNext()) {
					ids = ids +  ", ";
				}
				
			}
			ids = ids + "]";
			
			jsonStr = "{result: 'success', data: [ " + resultArray + " ], ids: " + ids + "}";
		} else {			
			jsonStr = "{result: 'failure'}";
		}
		
		request.setAttribute("result", jsonStr);	
		
		return mapping.findForward("display_result");
	}
}
